﻿//图像渲染(easy): https://leetcode.cn/problems/flood-fill/
class Solution {
public:
    typedef pair<int,int> PII;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};

    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
        int prev=image[sr][sc];
        if(prev==color)    return image;
        int m=image.size(); int n=image[0].size(); 
        queue<pair<int,int>> q;
        q.push({sr,sc});
        while(q.size())
        {
            auto& [a,b]=q.front();
            q.pop();
            image[a][b]=color;
            for(int k=0;k<4;k++)
            {
                int x=a+dx[k]; int y=b+dy[k];
                if(x>=0&&x<m&&y>=0&&y<n&&image[x][y]==prev)
                {
                    q.push({x,y});
                }
            }
        }
        return image;
    }
};

//岛屿数量(medium): https://leetcode.cn/problems/number-of-islands/description/
class Solution {
public:
    typedef pair<int,int> PII;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0}; 
    bool vis[310][310];
    queue<pair<int,int>> q;
    int n,m;
    int numIslands(vector<vector<char>>& grid) {
        int ret=0;
        m=grid.size(),n=grid[0].size();  
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(!vis[i][j]&&grid[i][j]=='1')
                {
                    ret++;
                    bfs(i,j,grid);
                }
            }
        }
        return ret;
    }
    void bfs(int i,int j,vector<vector<char>>& grid)
    {
        vis[i][j]=true;
        q.push({i,j});
        while(q.size())
        {
            auto [a,b]=q.front();
            q.pop();
            for(int k=0;k<4;k++)
            {
                int x=a+dx[k]; int y=b+dy[k];
                if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]=='1'&&!vis[x][y])
                {
                    vis[x][y]=true;
                    q.push({x,y});
                }
            }
        }
    }
};